import time
from aliyun.log import LogClient, PutLogsRequest, LogItem, logexception
import socket


class AliLog:
    project_endpoint = "cn-hangzhou.log.aliyuncs.com"
    log_store_name = ""
    log_topic = "default"
    log_source = ""

    # init
    def __init__(self, access_key=None, access_secret=None, project_name=None, log_store_name="services",
                 log_topic="default"):
        self.project_access_key_id = access_key
        self.project_access_key_secret = access_secret
        self.log_store_name = log_store_name
        self.project_name = project_name
        self.log_topic = log_topic
        if not access_key or not access_secret or not self.project_name:
            self.log_client = None
        else:
            self.log_client = LogClient(self.project_endpoint, self.project_access_key_id,
                                        self.project_access_key_secret)

        # 设置log_source
        self.log_source = self.get_host_ip()

    # 本地ip
    def get_host_ip(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 80))
            ip = s.getsockname()[0]
        finally:
            s.close()

        return ip

    # 仅仅是例子，不要直接使用
    # grpc_error :
    # @message : string
    def grpc_error(self, msg):
        if not self.log_client:
            print(msg)
            return

        contents = [
            ('level', "error"),
            ('msg', msg),
            ('time', time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime())),
        ]
        log_item = LogItem()
        log_item.set_time(int(time.time()))
        log_item.set_contents(contents)

        log_item_list = list()  # LogItem list
        log_item_list.append(log_item)

        return self.push_log_items(log_item_list)

    # push log
    # log_item_list = [self.get_log_item(), ....]
    def push_log_items(self, log_item_list=list()):

        request = PutLogsRequest(
                self.project_name,
                self.log_store_name,
                self.log_topic,
                self.log_source,
                log_item_list,
        )
        try:
            result = self.log_client.put_logs(request)
        except logexception.LogException as e:
            print("提交日志失败：" + str(e))
            return False
        return True
